package com.qf.sevice.Impl;

import com.qf.dao.Impl.OrderDaoImpl;
import com.qf.dao.Impl.OrderDetailDaoImpl;
import com.qf.dao.OrderDao;
import com.qf.dao.OrderDetailDao;
import com.qf.domain.Cart;
import com.qf.domain.Order;
import com.qf.domain.OrderDetail;
import com.qf.sevice.CartService;
import com.qf.sevice.OrderService;
import com.qf.utils.RandomUtils;
import com.qf.utils.TxUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class OrderServiceImpl implements OrderService {
    CartService cartService = new CartServiceImpl();
    OrderDao orderDao = new OrderDaoImpl();
    OrderDetailDao orderDetailDao = new OrderDetailDaoImpl();
    @Override
    public Order addOrder(int uid, String aid) {
        Connection conn = TxUtils.getConn();
        try {
            conn.setAutoCommit(false);
            List<Cart> carts = cartService.findCartByUid(uid);
            double sum = 0;
            for (Cart cart : carts) {
                sum += cart.getMoney();
            }
            Order order = new Order();
            //设置订单id
            order.setId(RandomUtils.createActive());
            order.setUid(uid);
            //订单总额
            order.setMoney(sum);
            order.setStatus("未支付");
            order.setTime(new Date());
            order.setAid(Integer.parseInt(aid));
            orderDao.insert(order);
            for (Cart cart : carts) {
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOid(order.getId());
                orderDetail.setPid(cart.getPid());
                orderDetail.setNum(cart.getNum());
                orderDetail.setMoney(cart.getMoney());
                orderDetailDao.insert(orderDetail);
            }
            cartService.clearCart(uid);
            conn.commit();
            return order;
        } catch (SQLException e) {
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } finally {
            try {
                TxUtils.remove();
                conn.setAutoCommit(true);
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public List<Order> findAllOrder() {
        return orderDao.findAllorder();
    }


}
